package com.ruoyi.pos.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.pos.domain.Goods;
import com.ruoyi.pos.domain.Order;
import com.ruoyi.pos.domain.OrderItem;
import com.ruoyi.pos.domain.Payment;
import com.ruoyi.pos.mapper.OrderMapper;
import com.ruoyi.pos.service.IGoodsService;
import com.ruoyi.pos.service.IOrderItemService;
import com.ruoyi.pos.service.IOrderService;
import com.ruoyi.pos.service.IPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * orderService业务层处理
 * 
 * @author wzh
 * @date 2021-04-19
 */
@Service
public class OrderServiceImpl implements IOrderService 
{
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IPaymentService paymentService;



    @Override
    public int generate(Map<String, Long> map) {
        Long opid = map.get("opid");
        Long cuid = map.get("cuid");
        Long shopid = map.get("shopid");
        Order order = new Order();
        order.setOrderCode(UUID.randomUUID().toString().replace("-", "").toLowerCase());
        order.setOpId(opid);
        order.setCuid(cuid);
        order.setShopId(shopid);
        order.setStatus(1);
        order.setCreateTime(new Date());
        orderMapper.insertOrder(order);
        System.out.println("##########################");
        System.out.println(order.getId());
        Order o2=orderService.selectOrderByCode(order.getOrderCode());

        return o2.getId().intValue();
    }

    @Override
    public Long addItem(Long oid, List<Long[]> ids) {
        OrderItem orderItem = new OrderItem();
        BigDecimal total = new BigDecimal(0);
        for (Long[] id:ids) {
            orderItem.setGid(id[0]);
            orderItem.setNumber(id[1]);
            orderItem.setOid(oid);
            Goods goods = goodsService.selectGoodsById(id[0]);
            try {
                //        购买后商品库存-1
                goods.setInventory(goods.getInventory() - 1);
            } catch (NullPointerException e) {
                throw new RuntimeException("不存在id="+id[0]+"的商品");
            }

            goodsService.updateGoods(goods);
            orderItem.setSalePrice(goods.getSalePrice());
            orderItem.setSubTotal(goods.getSalePrice().multiply(new BigDecimal(id[1])));
            total = total.add(orderItem.getSubTotal());
            orderItemService.insertOrderItem(orderItem);
        }
        Order order = orderService.selectOrderById(oid);
        order.setTotal(total);
        orderService.updateOrder(order);
//        返回受影响的订单id
        return order.getId();
    }

    @Override
    public Map<String, Object> getInfo(Long id) {
        Map<String,Object> result=new HashMap<>();
        List<Goods> goodsList = new ArrayList<>();
        Order order=orderService.selectOrderById(id);
        if (order == null) {
            result.put("errorMessage", "没有该id的订单");
            return result;
        }


        Payment payment = order!=null?paymentService.selectPaymentByOrderCode(order.getOrderCode()):null;;
        List<OrderItem> orderItemList = order!=null?orderItemService.selectOrderItemByCode(order.getOrderCode()):null;
        if (payment == null) {
            result.put("errorMessage", "该订单尚未支付");
        }
        if (orderItemList == null || orderItemList.size() == 0) {
            result.put("errorMessage", "该订单未添加商品");
        }
//        System.out.println(orderItemList.toString());
//        if (orderItemList!=null&&orderItemList.isEmpty() ) {
//            System.out.println(orderItemList.size());
//            for (OrderItem o :
//                    orderItemList) {
//                if(o!=null){
//                    long gid = o.getGid();
//                    Goods goods = goodsService.selectGoodsById(gid);
//                    goodsList.add(goods);
//                }
//            }
//        }
        order.setOrderItemList(orderItemList);

        result.put("payment", payment);
        result.put("order", order);

        return result;
    }

    @Override
    public Map<String, Object> getInfo(String code) {
        Map<String,Object> result=new HashMap<>();
        List<Goods> goodsList = new ArrayList<>();
        Order order=orderService.selectOrderByCode(code);
        if (order == null) {
            result.put("errorMessage", "没有该id的订单");
            return result;
        }
        System.out.println("#############################");
        System.out.println(order);

        Payment payment = order!=null?paymentService.selectPaymentByOrderCode(order.getOrderCode()):null;
        List<OrderItem> orderItemList = order!=null?orderItemService.selectOrderItemByCode(order.getOrderCode()):null;
        if (payment == null) {
            result.put("errorMessage", "该订单尚未支付");
        }
        if (orderItemList == null || orderItemList.size() == 0) {
            result.put("errorMessage", "该订单未添加商品");
        }
//        System.out.println(orderItemList.toString());
//        if (orderItemList!=null&&orderItemList.isEmpty() ) {
//            System.out.println(orderItemList.size());
//            for (OrderItem o :
//                    orderItemList) {
//                if(o!=null){
//                    long gid = o.getGid();
//                    Goods goods = goodsService.selectGoodsById(gid);
//                    goodsList.add(goods);
//                }
//            }
//        }
        order.setOrderItemList(orderItemList);

        result.put("payment", payment);
        result.put("order", order);
//        result.put("goods", goodsList);
        return result;
    }

    /**
     * 查询order
     * 
     * @param id orderID
     * @return order
     */
    @Override
    public Order selectOrderById(Long id)
    {
        return orderMapper.selectOrderById(id);
    }

    @Override
    public Order selectOrderByCode(String orderCode) {
        return orderMapper.selectOrderByCode(orderCode);
    }
    /**
     * 查询order列表
     * 
     * @param order order
     * @return order
     */
    @Override
    public List<Order> selectOrderList(Order order)
    {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增order
     * 
     * @param order order
     * @return 结果
     */
    @Transactional
    @Override
    public Long insertOrder(Order order)
    {
        order.setCreateTime(DateUtils.getNowDate());
        int rows = orderMapper.insertOrder(order);
        insertOrderItem(order);
        return order.getId();
    }

    /**
     * 修改order
     * 
     * @param order order
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOrder(Order order)
    {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除order
     * 
     * @param ids 需要删除的orderID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrderByIds(Long[] ids)
    {
        orderMapper.deleteOrderItemByOids(ids);
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除order信息
     * 
     * @param id orderID
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id)
    {
        orderMapper.deleteOrderItemByOid(id);
        return orderMapper.deleteOrderById(id);
    }

    /**
     * 新增item信息
     * 
     * @param order order对象
     */
    public void insertOrderItem(Order order)
    {
        List<OrderItem> orderItemList = order.getOrderItemList();
        Long id = order.getId();
        if (StringUtils.isNotNull(orderItemList))
        {
            List<OrderItem> list = new ArrayList<OrderItem>();
            for (OrderItem orderItem : orderItemList)
            {
                orderItem.setOid(id);
                list.add(orderItem);
            }
            if (list.size() > 0)
            {
                orderMapper.batchOrderItem(list);
            }
        }
    }
}
